package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Announcement;
import cn.wolfcode.mapper.AnnouncementMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IAnnouncementService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AnnouncementServiceImpl implements IAnnouncementService {

    @Autowired
    private AnnouncementMapper announcementMapper;


    @Override
    public void save(Announcement announcement) {
        announcementMapper.insert(announcement);
    }

    @Override
    public void delete(Long id) {
        announcementMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Announcement announcement) {
        announcementMapper.updateByPrimaryKey(announcement);
    }

    @Override
    public Announcement get(Long id) {
        return announcementMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Announcement> listAll() {
        return announcementMapper.selectAll();
    }

    @Override
    public PageInfo<Announcement> query(QueryObject qo) {
        //初始化数据库中状态为未读
        announcementMapper.InitRead();

        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Announcement> announcements = announcementMapper.selectForList(qo); //里面不需要自己写limit
        //找所有已读公告
        List<Long> anno_ids = announcementMapper.selectHasRead(UserContext.getCurrentUser().getId());
        for (Announcement announcement : announcements) {
            for (Long anno_id : anno_ids) {
                if(anno_id==announcement.getId()){
                    announcement.setIfread(true);
                }
            }
            announcementMapper.updateByPrimaryKey(announcement);
        }
        return new PageInfo<>(announcements);
    }

    @Override
    public void addHasRead(Long e_id, Long anno_id) {
        announcementMapper.addHasRead(e_id,anno_id);
    }

    @Override
    public List<Announcement> selectNoRead() {
        return announcementMapper.selectNoRead();
    }
}
